import { Inject } from '@nestjs/common';
import {
  ConnectedSocket,
  MessageBody,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
  WsResponse,
} from '@nestjs/websockets';
import { from, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Server, Socket } from 'socket.io';
import { AppService } from 'src/app.service';
import socketClientStore, { ClientEvent, SocketClientWrap } from './socket.client.store';

@WebSocketGateway({
  cors: {
    origin: '*',
  },
})
export class EventsGateway {
  @WebSocketServer()
  server: Server;

  handleConnection(client: Socket){
    socketClientStore.saveClientWrap(new SocketClientWrap(client, client.handshake.address))
  }

  handleDisconnect(client: Socket){
    // console.log(client)
    socketClientStore.removeById(client.id)
  }

  @SubscribeMessage('registerEvents')
  registerEvent(
    @MessageBody() data: ClientEvent[],
    @ConnectedSocket() client: Socket
  ): string {
    const clientWrap = socketClientStore.getById(client.id);
    clientWrap.registerEvents(data)
    return "register events success!";
  }

  @SubscribeMessage('events')
  findAll(
    @MessageBody() data: any
  ): Observable<WsResponse<number>> {
    return from([1, 2, 3]).pipe(map(item => ({ event: 'events', data: item })));
  }

  @SubscribeMessage('identity')
  async identity(@MessageBody() data: number): Promise<number> {
    return data;
  }
}
